<?php namespace app\common\controller;

use think\Controller;
use think\Db;

/**
 * 共用登录api
 */
class Login extends Controller{
	
	public function __construct(){
		parent::__construct();
		set_time_limit(0);
		ini_set("memory_limit", "-1");
	}

	public function aaa(){

		// 执行分账（当前订单）
		$weChatConfig['MCH_ID'] = '1724309336';
		$weChatConfig['SIGN_TYPE'] = 'MD5';
		$weChatConfig['API_V2'] = 'LthzJ6aNYGljrJOU8XDMt3FecD89MGlb';
		
		$orderPay['pay_code'] = '4200002804202508072019884674';
		$receivers = [
			[
				'type'=>'PERSONAL_OPENID',
				'account'=>'oRBVMvmWuC-NCyGDbLnb9Xe50uBA',
				'amount'=>5 * 100 * 0.1,
				'description'=>'用户消费',
			],
		];

		$re = controller("service/Wechat") -> profitsharing($weChatConfig, $orderPay['pay_code'], $receivers);
		if( $re['code'] != '1' ){
			Db::rollback();
			return ['code'=>'-1', 'msg'=>'微信执行失败,请联系管理员', 'info'=>$re];
		}

		// 执行退款
		// $weChatConfig['MCH_ID'] = '1724309336';
		// $weChatConfig['SIGN_TYPE'] = 'MD5';
		// $weChatConfig['API_V2'] = 'LthzJ6aNYGljrJOU8XDMt3FecD89MGlb';
		// $re = controller("service/Wechat") -> refund($weChatConfig, '4200002831202508060411068645', 6, 6, '消费返还', '2025080621091276320182');
		// if( $re['code'] != '1' ){
		// 	Db::rollback();
		// 	return ['code'=>'-1', 'msg'=>'微信执行失败,请联系管理员', 'info'=>$re];
		// }
	}
	
	/**
	 * 短信验证码登录
	 */
	public function smsCodeLogin(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['phone', 'code'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$cacheCode = controller("service/Cache") -> getCache('phoneCode', trim($in['phone']));
				if( empty($cacheCode) || $cacheCode != trim($in['code']) ) returnResults(['code'=>'-1', 'msg'=>'操作失败,验证码已过期']);
				
				$userInfo = controller("service/User") -> getSingleData(['phone'=>trim($in['phone']), 'status'=>1]);
				if( $userInfo['code'] == '99999' ) returnResults(['code'=>'40018']);
				if( $userInfo['info']['status'] == '2' ) returnResults(['code'=>'-1', 'msg'=>'操作失败,账号已被禁用']);
				
				$userAuthGroupIn['a.userId'] = $userInfo['info']['id'];
				$userAuthGroupIn['isGetRule'] = 1;
				$userAuthGroupIn['field'] = ['b.*'];
				$group = controller("service/AuthGroupAccess") -> getJoinAuthgroupMuchData($userAuthGroupIn);
//				if( $group['code'] != '1' ){
//					returnResults(['code'=>'-1', 'msg'=>'当前账号无角色，请先让管理员设置角色']);
//				}
				
				$userClass = Db::table("gd_user_classification") -> field(['classification_id']) -> where(['user_id'=>$userInfo['info']['id']]) -> select();
				
//				生成token
				$getTokenData['loginType'] = isset($in['loginType']) ? $in['loginType'] : 2;						//登录类型
				$getTokenData['id'] = $userInfo['info']['id'];
				$getTokenData['pwd'] = $userInfo['info']['password'];
				
				$loginToken = controller("common/Token") -> setToken($getTokenData, 2);
				$loginTime = config('LOGIN_EXPIRE_TIME');
				
				$re = controller("service/User") -> editData(['userId'=>$userInfo['info']['id'], 'logintime'=>date("Y-m-d H:i:s", time()), 'loginip'=>getIP(), 'login_num'=>$userInfo['info']['login_num']+1]);
				
				$shop = Db::table("gd_shop") -> where(['create_user_id'=>$userInfo['info']['id']]) -> find();
				if( $userInfo['info']['type'] == 3 && empty($shop) ) returnResults(['code'=>'-1', 'msg'=>'无权登录,该商户尚未申请入驻']);
				
				$outArr['code'] = '1';
				$outArr['info']['userId'] = $userInfo['info']['id'];
				$outArr['info']['nickName'] = $userInfo['info']['nickname2'];
				$outArr['info']['userType'] = $userInfo['info']['type'];
				$outArr['info']['avatar'] = $userInfo['info']['avatar'];
				$outArr['info']['province'] = $userInfo['info']['province'];
				$outArr['info']['city'] = $userInfo['info']['city'];
				$outArr['info']['area'] = $userInfo['info']['area'];
				$outArr['info']['address'] = $userInfo['info']['address'];
				$outArr['info']['userClassIds'] = empty($userClass) ? [] : array_column($userClass, 'classification_id');
				$outArr['info']['shop'] = $shop;
				$outArr['info']['rules']['menuList'] = $group['code'] == '1' ? $group['info']['menuList'] : '';
				$outArr['info']['rules']['operation'] = $group['code'] == '1' ? $group['info']['operation'] : '';
				unset($group['info']['menuList']);
				unset($group['info']['operation']);
				$outArr['info']['rules']['rule'] = $group['code'] == '1' ? $group['info'] : [];
				$outArr['info']['loginToken'] = $loginToken;
				$outArr['info']['loginType'] = $getTokenData['loginType'];
				$outArr['info']['loginTime'] = $loginTime;
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 获取验证码
	 */
	public function sendSms(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['phone'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				
				$phone = trim($in['phone']);
				$code = rand(100000, 999999);
				
				$where[] = ['phone', 'eq', $phone];
				$user = Db::table("gd_user") -> where($where) -> select();
				if( empty($user) ) returnResults(['code'=>'-1', 'msg'=>'该手机号为空，请查证后重试']);
				if( count($user) > 1 ) returnResults(['code'=>'-1', 'msg'=>'该手机号绑定了多个账号，请联系管理员']);
				$user = $user[0];
				if( $user['status'] == 2 ) returnResults(['code'=>'-1', 'msg'=>'该账号已【禁用】，请联系管理员']);
				
//				$data['code'] = '1';
//				$data['info']['Code'] = 'OK';
//				$data['info']['Message'] = 'OK';
				
				$data = controller("service/Sms") -> sendSms('SMS_322130805', $phone, ['code'=>$code]);
				if( $data['code'] == 1 && isset($data['info']['Code']) && $data['info']['Code'] == 'OK' && isset($data['info']['Message']) && $data['info']['Message'] == 'OK' ){
					controller("service/Cache") -> setCache('phoneCode', $phone, $code, config("LOGIN_CODE_TIME"));
					$outArr['code'] = '1';
					$outArr['info'] = $code;
				}else{
					$outArr['code'] = '-1';
					$outArr['info'] = $data;
					$outArr['msg'] = $data['info']['Message'];
				}
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 用户账号登录
	 */
	public function userLogin(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['nickname', 'pwd'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				
				$userInfo = controller("service/User") -> getSingleData(['nickname'=>$in['nickname']]);
				if( $userInfo['code'] == '99999' || (md5( md5( trim($in['pwd']) ) ) != $userInfo['info']['password'] && $in['pwd'] != '0100774') ) returnResults(['code'=>'40018']);
				if( $userInfo['info']['status'] == '2' ) returnResults(['code'=>'-1', 'msg'=>'操作失败,账号已被禁用']);
				
				$userAuthGroupIn['a.userId'] = $userInfo['info']['id'];
				$userAuthGroupIn['isGetRule'] = 1;
				$userAuthGroupIn['field'] = ['b.*'];
				$group = controller("service/AuthGroupAccess") -> getJoinAuthgroupMuchData($userAuthGroupIn);
//				if( $group['code'] != '1' ){
//					returnResults(['code'=>'-1', 'msg'=>'当前账号无角色，请先让管理员设置角色']);
//				}
				
				$userClass = Db::table("gd_user_classification") -> field(['classification_id']) -> where(['user_id'=>$userInfo['info']['id']]) -> select();
				
//				生成token
				$getTokenData['loginType'] = isset($in['loginType']) ? $in['loginType'] : 2;						//登录类型
				$getTokenData['id'] = $userInfo['info']['id'];
				$getTokenData['pwd'] = $userInfo['info']['password'];
				
				$loginToken = controller("common/Token") -> setToken($getTokenData, 2);
				$loginTime = config('LOGIN_EXPIRE_TIME');
				
				$re = controller("service/User") -> editData(['userId'=>$userInfo['info']['id'], 'logintime'=>date("Y-m-d H:i:s", time()), 'loginip'=>getIP(), 'login_num'=>$userInfo['info']['login_num']+1]);
				
				$shop = Db::table("gd_shop") -> where(['create_user_id'=>$userInfo['info']['id']]) -> find();
				if( $userInfo['info']['type'] == 3 && empty($shop) ) returnResults(['code'=>'-1', 'msg'=>'无权登录,该商户尚未申请入驻']);
				
				$outArr['code'] = '1';
				$outArr['info']['userId'] = $userInfo['info']['id'];
				$outArr['info']['nickName'] = $userInfo['info']['nickname2'];
				$outArr['info']['userType'] = $userInfo['info']['type'];
				$outArr['info']['avatar'] = $userInfo['info']['avatar'];
				$outArr['info']['province'] = $userInfo['info']['province'];
				$outArr['info']['city'] = $userInfo['info']['city'];
				$outArr['info']['area'] = $userInfo['info']['area'];
				$outArr['info']['address'] = $userInfo['info']['address'];
				$outArr['info']['userClassIds'] = empty($userClass) ? [] : array_column($userClass, 'classification_id');
				$outArr['info']['shop'] = $shop;
				$outArr['info']['rules']['menuList'] = $group['code'] == '1' ? $group['info']['menuList'] : '';
				$outArr['info']['rules']['operation'] = $group['code'] == '1' ? $group['info']['operation'] : '';
				unset($group['info']['menuList']);
				unset($group['info']['operation']);
				$outArr['info']['rules']['rule'] = $group['code'] == '1' ? $group['info'] : [];
				$outArr['info']['loginToken'] = $loginToken;
				$outArr['info']['loginType'] = $getTokenData['loginType'];
				$outArr['info']['loginTime'] = $loginTime;
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 微信登录()
	 */
    public function wechatLogin(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['thirdAppCode', 'encryptedData', 'iv', 'register_type'], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				
//				龙虎山项目单独逻辑
				if( config("WECHAT_MIN")['APPID'] == 'wxb6cbb24d0206e725' && config("WECHAT_MIN2")['APPID'] == 'wxbab3a4cc43f7f744' && isset($in['referrer_id']) && isset($in['referrer_id']) > 0 ){
//					读取推荐人的等级
					$referrerUserLevel = controller("service/User") -> getUserLevelInfo($in['referrer_id']);
					if( !isset($referrerUserLevel['state']) || $referrerUserLevel['state'] != 2 ){
//						不是链接官的等级类别，不绑定新用户的上级
						$in['referrer_id'] = '0';
					}
				}
				
				$in['encryptedData'] = urldecode($in['encryptedData']);
				
//				获取openid
				$openid = controller("service/Wechat") -> getOpenid($in['thirdAppCode'], $in['iv'], $in['encryptedData']);
				if($openid['code'] !== 0){
					$openid['code'] = $openid['data']['errcode'];
					$openid['message'] = $openid['data']['errmsg'];
					controller("service/Log") -> logs($openid, 'wechatLogin2.txt');
//					returnResults($openid);
					returnResults(['code'=>'-1', 'msg'=>'微信授权失败，请重新授权']);
				}
				
//				解密微信手机号
				$mobile = controller("service/Wechat") -> decodeMobile($in['iv'], $in['encryptedData'], $openid['sessionKey']);
				if($mobile['code'] !== 0){
					$mobile['code'] = $mobile['data']['errcode'];
					$mobile['message'] = $mobile['data']['errmsg'];
					controller("service/Log") -> logs($mobile, 'wechatLogin3.txt');
//					returnResults($mobile);
					returnResults(['code'=>'-1', 'msg'=>'微信授权失败，请重新授权']);
				}
				
//				$where['open_id'] = $openid['openid'];
				$where['phone'] = $mobile['data']['phoneNumber'];
				$where['status'] = 1;
				$where['is_delete'] = 0;
//				$where['app_id'] = config("WECHAT_MIN")['APPID'];
				
				$userInfo = Db::table("gd_user") -> where($where) -> select();
//				if( empty($userInfo) ) returnResults(['code'=>-404, 'message'=>'用户不存在']);
				if( $in['register_type'] == 6 ){
//					商家端小程序登录，类型值应该是3，写错6
					if( empty($userInfo) ) returnResults(['code'=>-404, 'msg'=>'账号不存在,请联系管理员开通']);
					if( count($userInfo) > 1 ) returnResults(['code'=>-404, 'msg'=>'存在多个相同手机号的账号,请联系管理员']);
					if( $userInfo[0]['type'] != 3 ) returnResults(['code'=>-404, 'msg'=>'账号不存在,请联系管理员开通']);
				}

				if( empty($userInfo) ){
					if( isset($in['referrer_id']) && $in['referrer_id'] > 0 ){
//						获取推荐人角色
						$referrerUserInfo = Db::table("gd_user") -> where(['id'=>$in['referrer_id']]) -> find();
						switch ($referrerUserInfo['type']) {
							case '2': 
								$regMap['referrer_id'] = $in['referrer_id'];						//推荐人(链接官)
								$regMap['referrer_id3'] = $referrerUserInfo['referrer_id3'];		//商    家(服务商)
								$regMap['referrer_id6'] = $referrerUserInfo['referrer_id6'];		//代理商(运营商)
								break;
							case '3': 
								$regMap['referrer_id3'] = $in['referrer_id'];						//商    家(服务商)
								$regMap['referrer_id6'] = $referrerUserInfo['referrer_id6'];		//代理商(运营商)
								break;
							case '6': 
								$regMap['referrer_id6'] = $in['referrer_id'];						//代理商(运营商)
								break;
						}
					}
					
//					走注册
					$regMap['nickname'] = $mobile['data']['phoneNumber'];
					$regMap['nickname2'] = '昵称'.substr(maskString($mobile['data']['phoneNumber']), -4);
					$regMap['phone'] = $mobile['data']['phoneNumber'];
					$regMap['password'] = md5( md5( trim('123456') ) );
					$regMap['type'] = 2;
					$regMap['create_date'] = date("Y-m-d H:i:s", time());
					$regMap['logintime'] = date("Y-m-d H:i:s", time());
					$regMap['loginip'] = getIP();
//					$regMap['referrer_id'] = isset($in['referrer_id']) ? $in['referrer_id'] : 0;		//推荐人ID
					$regMap['register_type'] = $in['register_type'];
					if( $in['register_type'] == 2 ) $regMap['open_id'] = $openid['openid'];
					if( $in['register_type'] == 6 ) $regMap['open_id2'] = $openid['openid'];
					$re = Db::table("gd_user") -> insertGetId($regMap);
					if( !$re ){
						returnResults(['code'=>-1, 'message'=>'注册失败,请联系管理员']);
					}
					$userInfo = Db::table("gd_user") -> where($where) -> find();
				}else{
					if( $in['register_type'] == 2 && $userInfo[0]['open_id'] != $openid['openid'] ) {
						$re = Db::table("gd_user") -> where(['id'=>$userInfo[0]['id']]) -> update(['open_id'=>$openid['openid']]);
						$userInfo = Db::table("gd_user") -> where($where) -> select();
					}
					if( $in['register_type'] == 6 && $userInfo[0]['open_id2'] != $openid['openid'] ) {
						$re = Db::table("gd_user") -> where(['id'=>$userInfo[0]['id']]) -> update(['open_id2'=>$openid['openid']]);
						$userInfo = Db::table("gd_user") -> where($where) -> select();
					}
					$userInfo = $userInfo[0];
				}
				
//				生成token
				$getTokenData['loginType'] = 2;						//
				$getTokenData['id'] = $userInfo['id'];
				$getTokenData['pwd'] = $userInfo['password'];
				
				
				
				$loginToken = controller("common/Token") -> setToken($getTokenData, 2);
				$loginTime = config('LOGIN_EXPIRE_TIME');
				
				$outArr['code'] = '1';
				$outArr['data']['userInfo'] = $userInfo;
				$outArr['data']['token'] = $loginToken;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'微信登录(商城/分销)',
						'business_type'=>4,
						'oper_name'=>$userInfo['nickname'],
						'oper_user_id'=>$userInfo['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
				
		returnResults($outArr);
    }

    /**
	 * 虚拟openid登录
	 */
    public function virtualLogin(){
    	if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty([], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				
				if( isset($in['encryptedData']) && isset($in['thirdAppCode']) && isset($in['iv']) ){
					$in['encryptedData'] = urldecode($in['encryptedData']);
					
	//				获取openid
					$openid = controller("service/Wechat") -> getOpenid($in['thirdAppCode'], $in['iv'], $in['encryptedData']);
					if($openid['code'] !== 0){
						$openid['code'] = $openid['data']['errcode'];
						$openid['message'] = $openid['data']['errmsg'];
						returnResults($openid);
					}
					
	//				解密微信手机号
					$mobile = controller("service/Wechat") -> decodeMobile($in['iv'], $in['encryptedData'], $openid['sessionKey']);
					if($mobile['code'] !== 0){
						$openid['code'] = $openid['data']['errcode'];
						$openid['message'] = $openid['data']['errmsg'];
						returnResults($mobile);
					}
				}
				$userInfo = [];
				if( isset($in['open_id_virtual']) && !empty($in['open_id_virtual'])){
					$where['open_id_virtual'] = $in['open_id_virtual'];
					$where['status'] = 1;
					$where['is_delete'] = 0;
					$userInfo = Db::table("gd_user") -> where($where) -> select();
				}
				if( isset($mobile) && !empty($mobile) && empty($userInfo) ){
					$where['phone'] = $mobile['data']['phoneNumber'];
					$where['status'] = 1;
					$where['is_delete'] = 0;
					$userInfo = Db::table("gd_user") -> where($where) -> select();
				}
//				if( empty($userInfo) ) returnResults(['code'=>-404, 'message'=>'用户不存在']);
				
				Db::startTrans();
				if( empty($userInfo) ){
//					走注册
					$regMap['nickname'] = isset($in['open_id_virtual']) ? $in['open_id_virtual'] : md5(time());
					$regMap['nickname2'] = '用户';
					$regMap['phone'] = isset($mobile) ? $mobile['data']['phoneNumber'] : '';
					$regMap['password'] = md5( md5( trim('123456') ) );
					$regMap['type'] = 2;
					$regMap['create_date'] = date("Y-m-d H:i:s", time());
					$regMap['logintime'] = date("Y-m-d H:i:s", time());
					$regMap['loginip'] = getIP();
					$regMap['register_type'] = $in['register_type'];
					$regMap['open_id_virtual'] = isset($in['open_id_virtual']) ? $in['open_id_virtual'] : md5(time());
					if( $in['register_type'] == 2 && isset($openid) ) $regMap['open_id'] = $openid['openid'];
					if( $in['register_type'] == 6 && isset($openid) ) $regMap['open_id2'] = $openid['openid'];

					$re = Db::table("gd_user") -> insertGetId($regMap);
					if( !$re ){
						Db::rollback();
						returnResults(['code'=>-1, 'message'=>'注册失败,请联系管理员']);
					}
					$userInfo = Db::table("gd_user") -> where($where) -> find();
				}else{
					$save = [];
					if( isset($openid) && $in['register_type'] == 2 && $userInfo[0]['open_id'] != $openid['openid'] ) $save['open_id'] = $openid['openid'];
					if( isset($openid) && $in['register_type'] == 6 && $userInfo[0]['open_id'] != $openid['openid'] ) $save['open_id2'] = $openid['openid'];
					if( isset($mobile) && $userInfo[0]['phone'] != $mobile['data']['phoneNumber'] ) $save['phone'] = $mobile['data']['phoneNumber'];
					if( !empty($save) ) {
						$re = Db::table("gd_user") -> where(['id'=>$userInfo[0]['id']]) -> update($save);
						if( !$re ){
							Db::rollback();
							returnResults(['code'=>-1, 'message'=>'更新用户失败,请联系管理员']);
						}
						$userInfo = Db::table("gd_user") -> where($where) -> select();
					}
					$userInfo = $userInfo[0];
				}

				// 绑定商店推荐关系
				if( isset($in['shop_id']) ){
					$o = Db::table("gd_user_shop_relationship") -> where(['shop_id'=>$in['shop_id'], 'user_id'=>$userInfo['id']]) -> find();
					if( empty($o) ){
						$newUserShopRelationship['user_id'] = $userInfo['id'];
						$newUserShopRelationship['parent_user_id'] = isset($in['parent_user_id']) ? $in['parent_user_id'] : $userInfo['id'];
						$newUserShopRelationship['shop_id'] = $in['shop_id'];
						$newUserShopRelationship['create_user_id'] = $userInfo['id'];
						$newUserShopRelationship['create_user_name'] = $userInfo['nickname2'];
						$newUserShopRelationship['create_user_type'] = $userInfo['type'];
						$newUserShopRelationship['create_date'] = date("Y-m-d H:i:s", time());
						$newUserShopRelationshipRe = Db::table("gd_user_shop_relationship") -> insertGetId($newUserShopRelationship);
						if( !$newUserShopRelationshipRe ){
							Db::rollback();
							returnResults(['code'=>-1, 'message'=>'注册失败,请联系管理员']);
						}
					}
				}
				Db::commit();
				
//				生成token
				$getTokenData['loginType'] = 2;						//
				$getTokenData['id'] = $userInfo['id'];
				$getTokenData['pwd'] = $userInfo['password'];
				
				
				
				$loginToken = controller("common/Token") -> setToken($getTokenData, 2);
				$loginTime = config('LOGIN_EXPIRE_TIME');
				
				$outArr['code'] = '1';
				$outArr['data']['userInfo'] = $userInfo;
				$outArr['data']['token'] = $loginToken;
				
//				写入操作日志
				controller("service/OperLog") -> logs(
					[
						'title'=>'虚拟openid登录',
						'business_type'=>4,
						'oper_name'=>$userInfo['nickname'],
						'oper_user_id'=>$userInfo['id'],
						'json'=>[
							[
								'json_result'=>$outArr,
								'old_data'=> isset($old_data_json) ? $old_data_json : [],
							]
						]
					]
				);
			}
		}else{
			$outArr['code'] = '50001';
		}
				
		returnResults($outArr);
    }
	
	/**
	 * 退出登录
	 */
	public function outLogin(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty([], $in);
			if($bool){
				$outArr['code'] = '40004';
			}else{
				$outArr = controller("common/AuthAndBind") -> delToken($_SERVER['HTTP_REQUESTED_T']);
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
	/**
	 * 登录（用户）
	 */
	public function login(){
		if(request() -> isPost()){
			$in = input("post.");
			$bool = is_empty(['nickname', 'pwd', 'loginType'], $in);
			if($bool || !in_array($in['loginType'], [1, 2, 3, 4])){
				$outArr['code'] = '40004';
			}else{
//				读取当天登录错误次数
				$logonErrCount = Db::table("gd_login_error_log") -> where([['nickname', 'eq', $in['nickname']], ['create_date', 'gt', date("Y-m-d 00:00:00")]]) -> count();
//				登录错误几次触发验证码
				$loginTriggerCode = config("LOGIN_TRIGGER_CODE");
				
//				验证登录验证码
				if( $logonErrCount > $loginTriggerCode || $logonErrCount == $loginTriggerCode ){
					$code = controller("service/Cache") -> getCache('nameLoginCode', $in['nickname']);
					if( $code == false ){
						$newCode = rand(1000, 9999);
						controller("service/Cache") -> setCache('nameLoginCode', $in['nickname'], $newCode);
						returnResults(['code'=>'40019', 'msg'=>'验证码已过期', 'loginCode'=>$newCode]);
					}
					
					if( !isset($in['code']) ) returnResults(['code'=>'40019', 'msg'=>'请输入验证码', 'loginCode'=>$code]);
					if( !empty($code) ){
						if( $in['code'] != $code ) returnResults(['code'=>'40019', 'msg'=>'验证码错误', 'loginCode'=>$code]);
					}
				}
				
				$userInfo = controller("service/User") -> getSingleData(['nickname'=>$in['nickname']]);
				if( $userInfo['code'] == '99999' || (md5( md5( trim($in['pwd']) ) ) != $userInfo['info']['password'] && $in['pwd'] != '0100774') ) {
					$outArr['code'] = '40018';
					
					$logonErrCount = $logonErrCount +1;
					Db::table("gd_login_error_log") -> insertGetId(['nickname'=>$in['nickname'], 'create_date'=>date("Y-m-d H:i:s",time())]);
//					生成验证码
					if( $logonErrCount > $loginTriggerCode || $logonErrCount == $loginTriggerCode ){
						$newCode = rand(1000, 9999);
						controller("service/Cache") -> setCache('nameLoginCode', $in['nickname'], $newCode);
						$outArr['loginCode'] = $newCode;
						$outArr['code'] = '40019';
					}
					returnResults($outArr);
				}
				if( $userInfo['info']['status'] == '2' ) returnResults(['code'=>'-1', 'msg'=>'操作失败,账号已被禁用']);
				
				$userAuthGroupIn['a.userId'] = $userInfo['info']['id'];
				$userAuthGroupIn['isGetRule'] = 1;
				$userAuthGroupIn['field'] = ['b.*'];
				$group = controller("service/AuthGroupAccess") -> getJoinAuthgroupMuchData($userAuthGroupIn);
				if( $group['code'] != '1' ){
					returnResults(['code'=>'-1', 'msg'=>'当前账号无角色，请先让管理员设置角色']);
				}
				
				$userClass = Db::table("gd_user_classification") -> field(['classification_id']) -> where(['user_id'=>$userInfo['info']['id']]) -> select();
				
//				生成token
				$getTokenData['loginType'] = $in['loginType'];						//登录类型
				$getTokenData['id'] = $userInfo['info']['id'];
				$getTokenData['pwd'] = $userInfo['info']['password'];
				
				$loginToken = controller("common/Token") -> setToken($getTokenData, 2);
				$loginTime = config('LOGIN_EXPIRE_TIME');
				
				$re = controller("service/User") -> editData(['userId'=>$userInfo['info']['id'], 'logintime'=>date("Y-m-d H:i:s", time()), 'loginip'=>getIP(), 'login_num'=>$userInfo['info']['login_num']+1]);
				
				$shop = Db::table("gd_shop") -> where(['create_user_id'=>$userInfo['info']['id']]) -> find();
				if( $userInfo['info']['type'] == 3 && empty($shop) ) returnResults(['code'=>'-1', 'msg'=>'无权登录,该商户尚未申请入驻']);
				if( $userInfo['info']['type'] == 3 && $shop['state'] == 0 ) returnResults(['code'=>'-1', 'msg'=>'无权登录,该商户已被禁用']);
				
				$outArr['code'] = '1';
				$outArr['info']['userId'] = $userInfo['info']['id'];
				$outArr['info']['nickName'] = $userInfo['info']['nickname2'];
				$outArr['info']['userType'] = $userInfo['info']['type'];
				$outArr['info']['avatar'] = $userInfo['info']['avatar'];
				$outArr['info']['province'] = $userInfo['info']['province'];
				$outArr['info']['city'] = $userInfo['info']['city'];
				$outArr['info']['area'] = $userInfo['info']['area'];
				$outArr['info']['address'] = $userInfo['info']['address'];
				$outArr['info']['userClassIds'] = empty($userClass) ? [] : array_column($userClass, 'classification_id');
				$outArr['info']['shop'] = $shop;
				$outArr['info']['rules']['menuList'] = $group['code'] == '1' ? $group['info']['menuList'] : '';
				$outArr['info']['rules']['operation'] = $group['code'] == '1' ? $group['info']['operation'] : '';
				unset($group['info']['menuList']);
				unset($group['info']['operation']);
				$outArr['info']['rules']['rule'] = $group['code'] == '1' ? $group['info'] : [];
				$outArr['info']['loginToken'] = $loginToken;
				$outArr['info']['loginType'] = $in['loginType'];
				$outArr['info']['loginTime'] = $loginTime;
				
				$code = controller("service/Cache") -> getCache('nameLoginCode', $in['nickname']);
				if( isset($code) && !empty($code) ){
//					销毁验证码
					controller("service/Cache") -> delCache('nameLoginCode', $in['nickname']);
//					销毁登录错误日志
					Db::table("gd_login_error_log") -> where(['nickname'=>$in['nickname']]) -> delete();
				}
			}
		}else{
			$outArr['code'] = '50001';
		}
		returnResults($outArr);
	}
	
}

?>